package com.mec.web.y2012.ajax;

import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

@WebServlet("/ajax/employeeList")
public class EmployeeListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public EmployeeListServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		
		if("add".equals(action)){
			addEmployee(request, response);
		}else if("delete".equals(action)){
			deleteEmployee(request, response);
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	
	private void addEmployee(HttpServletRequest request, HttpServletResponse response) throws IOException{
		String uniqueID = storeEmployee();
		
		//
		StringBuffer xml = new StringBuffer("<result><uniqueID>");
		xml.append(uniqueID);
		xml.append("</uniqueID>");
		xml.append("</result>");
		
		sendResponse(response, xml.toString());
	}
	
	private void deleteEmployee(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		String id = request.getParameter("id");
		
		StringBuffer xml = new StringBuffer("<result>");
		xml.append("<status>1</status>");
		xml.append("</result>");
		
		sendResponse(response, xml.toString());
	}
	
	private String storeEmployee(){
		String uniqueID = "";
		
		Random randomizer = new Random(System.currentTimeMillis());
		for(int i = 0 ; i <8 ; ++i){
			//uniqueID += Math.abs(randomizer.nextInt());
			uniqueID += randomizer.nextInt();
		}
		
		return uniqueID;
	}
	private void sendResponse(HttpServletResponse response, String responseText) throws IOException{
		response.setContentType("text/xml");
		response.getWriter().write(responseText);
		
	}

	private static final Logger logger = 
			Logger.getLogger(EmployeeListServlet.class);
}
